package com.cskaoyan.controller.wx.lxc;

import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.bean.po.MarketAddress;
import com.cskaoyan.bean.po.MarketUser;
import com.cskaoyan.service.wx.lxc.WxAddressService;
import com.cskaoyan.util.StringUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("wx/address")
public class WxAddressController {

    @Autowired
    WxAddressService wxAddressService;

    @RequestMapping("list")
    public BaseRespVo queryAddressList() {
        CommonData<MarketAddress> commonData = wxAddressService.queryAddressList();
        return BaseRespVo.succeed(commonData);
    }

    @RequestMapping("save")
    public BaseRespVo saveAddress(@RequestBody MarketAddress marketAddress) {
        if (marketAddress.getTel().length() != 11) {
            return BaseRespVo.invalidParameter("请输入正确的11位手机号！");
        }
        if (StringUtil.isEmpty(marketAddress.getAddressDetail())) {
            return BaseRespVo.invalidParameter("详细地址不能为空！");
        }
        Subject subject = SecurityUtils.getSubject();
        MarketUser primaryPrincipal = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        int id = wxAddressService.saveAddress(marketAddress, primaryPrincipal.getId());
        if (id == 0) {
            return BaseRespVo.invalidParameter("添加失败！请重试！");
        }
        return BaseRespVo.succeed(id);
    }

    @RequestMapping("detail")
    public BaseRespVo detailAddress(Integer id) {
        MarketAddress marketAddress = wxAddressService.detailAddress(id);
        return BaseRespVo.succeed(marketAddress);
    }

    @RequestMapping("delete")
    public BaseRespVo deleteAddress(@RequestBody MarketAddress marketAddress) {
        int code = wxAddressService.deleteAddress(marketAddress.getId());
        if (code == 0) {
            return BaseRespVo.invalidParameter("删除失败！请重试！");
        }
        return BaseRespVo.succeed();
    }
}
